package top.xzxsrq.datahelp.zhixin.module.socket.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import top.xzxsrq.datahelp.zhixin.module.socket.WebSocketSessionManager;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 发送消息服务类
 *
 * @program: datahelp
 * @create: 2021-11-09 20:38
 **/
@Service
@Slf4j
public class WebSocketService {
    /**
     * 发送消息
     *
     * @param session
     * @param text
     * @return
     * @throws IOException
     */
    public void sendMsg(WebSocketSession session, String text) throws IOException {
        session.sendMessage(new TextMessage(text));
    }

    /**
     * 广播消息
     *
     * @param text
     * @return
     * @throws IOException
     */
    public void broadcastMsg(String text) throws IOException {
        for (WebSocketSession session : WebSocketSessionManager.SESSION_POOL.values()) {
            session.sendMessage(new TextMessage(text));
        }
    }

    /**
     * 发送二进制
     *
     * @param session
     * @param in
     * @throws IOException
     */
    public void sendMsg(WebSocketSession session, InputStream in) throws IOException {
        byte[] bytes = IOUtils.toByteArray(in);
        session.sendMessage(new BinaryMessage(bytes));
    }

    /**
     * 广播消息二进制
     *
     * @param in
     * @throws IOException
     */
    public void broadcastMsg(InputStream in) throws IOException {
        byte[] bytes = IOUtils.toByteArray(in);
        for (WebSocketSession session : WebSocketSessionManager.SESSION_POOL.values()) {
            session.sendMessage(new BinaryMessage(bytes));
        }
    }

    public void broadcastMsgNotId(String text, List<String> ids) throws IOException {
        List<WebSocketSession> collect = WebSocketSessionManager.SESSION_POOL
                .values()
                .stream()
                .filter(i -> !ids.contains(i.getId()))
                .collect(Collectors.toList());
        for (WebSocketSession session : collect) {
            session.sendMessage(new TextMessage(text));
        }
    }
}
